import SparkMD5 from 'spark-md5';

onmessage = async (e) => {
    const {file} = e.data;
    const chunkSize = 1024 * 1024; // 1MB
    const size = file.size;
    let spark = new SparkMD5.ArrayBuffer();
    let fileReader = new FileReader();
    if (size > chunkSize) {
        let chunks = [];
        let finish = 0;
        for (let i = 0; i < size; i += chunkSize) {
            let end = i + chunkSize;
            chunks.push(file.slice(i, end));
        }
        const load = () => {
            fileReader.readAsArrayBuffer(chunks[finish]);
        }
        fileReader.onload = (e) => {
            spark.append(e.target.result)
            finish++;
            if (finish === chunks.length) {
                postMessage({md5: spark.end()})
            } else {
                load()
                postMessage({})
            }
        }
        load()
    } else {
        fileReader.onload = (e) => {
            spark.append(e.target.result)
            postMessage({md5: spark.end()})
        }
        // 开始读取文件
        fileReader.readAsArrayBuffer(file);
    }
}